import { View } from '@tarojs/components';
import { Button, Dialog, Input } from '@nutui/nutui-react-taro';
import { useState } from 'react';
import { getUser } from '@/utils/user';
import Taro from '@tarojs/taro';
import request from '@/utils/request';
import './index.less';

interface IProps {
  onTabbarChange: (index: number) => void;
}

export default function Index(props: IProps) {
  const [shareLink, setShareLink] = useState('');
  const [createDialogVisible, setCreateDialogVisible] = useState(false);
  const [confirmDialogVisible, setConfirmDialogVisible] = useState(false);

  const goCreate = () => {
    setConfirmDialogVisible(true);
  };

  const handleConfirmCreate = async () => {
    const user = getUser();
    try {
      if (!shareLink) {
        Taro.showToast({
          title: '请完善创建信息',
          icon: 'none',
        });
        return;
      }

      setConfirmDialogVisible(false);
      setCreateDialogVisible(true);
      await request.post('/work/createWorkGetText', {
        userId: user.id,
        shareLink,
      });
    } catch (error) {
      console.error('创建失败:', error);
      Taro.showToast({
        title: '创建失败，请重试',
        icon: 'none',
      });
    }
  };

  return (
    <View className="dou-create">
      <View>
        <View className="share-link">
          <View className="title">分享链接</View>
          <Input
            className="link-input"
            placeholder="请输入分享链接"
            value={shareLink}
            onChange={(val) => setShareLink(val)}
          />
        </View>

        <View className="create-button">
          <Button block type="primary" onClick={goCreate}>
            <View className="button-content">
              <View className="text">创建</View>
            </View>
          </Button>
        </View>

        <View className="title">
          <View className="icon" />
          使用说明
        </View>
        <View className="content primary">1. 获取抖音作品的分享连接</View>
        <View className="content primary">2. 等待提取完成</View>
      </View>

      <Dialog
        title="确认创建"
        visible={confirmDialogVisible}
        onConfirm={handleConfirmCreate}
        onCancel={() => setConfirmDialogVisible(false)}>
        <View style={{ padding: '16px' }}>
          <View>确认创建该作品吗？</View>
        </View>
      </Dialog>

      <Dialog
        title="作品创作中"
        visible={createDialogVisible}
        footerDirection="vertical"
        hideCancelButton={true}
        confirmText="去查看"
        onConfirm={() => {
          setCreateDialogVisible(false);
          props.onTabbarChange(1);
        }}>
        <View style={{ height: 70, padding: 10 }}>
          <View style={{ textAlign: 'center', marginTop: 10 }}>
            大约需要5-10分钟时间
          </View>
          <View style={{ textAlign: 'center', marginTop: 10 }}>
            可以去作品列表查看作品状态
          </View>
        </View>
      </Dialog>
    </View>
  );
}
